import pymysql
from pymysql import cursors

from utils.Common import Common


# 数据库操作类
class DBOper:
    __host = ''
    __user = ''
    __password = ''
    __port = 0
    __db = None
    __conn = None
    __cur = None
    __charset = ''

    def __init__(self, host, user, password, port, db, charset='utf-8'):
        self.__host = host
        self.__user = user
        self.__password = password
        self.__port = port
        self.__db = db
        self.__charset = charset

    # 连接数据库
    def connect(self, curType = cursors.DictCursor):
        self.__conn = pymysql.connect(
            host=self.__host,
            user=self.__user,
            password=self.__password,
            port=self.__port,
            db=self.__db
        )
        self.__cur = self.__conn.cursor(curType)
        return self

    # 获取conn cur对象
    def getConnect(self):
        return self.__conn

    def getCursor(self):
        return self.__cur

    def close(self):
        self.__conn.close()

    # 读取
    def read(self, sql, type='all'):
        self.__cur.execute(sql)
        if type == 'all':
            result = self.__cur.fetchall()
        elif type == 'one':
            result = self.__cur.fetchone()
        else: result = self.__cur.fetchmany(size=Common.toInt(type))
        return result

    # 写入
    def write(self, sql, transaction=True):
        count = 0
        sqls = []
        if type(sql) == list: sqls.extend(sql)
        else: sqls.append(sql)
        try:
            for s in sqls:
                count += self.__cur.execute(s)
            self.submit()
        except Exception as e:
            if transaction: self.__conn.rollback()
            else: self.submit()
            raise e
        return count

    def writeOne(self, sql, autoSubmit = False):
        count = self.__cur.execute(sql)
        if autoSubmit: self.submit()
        return count

    # 更换数据库
    def changeDB(self, db):
        self.close()
        self.__db = db
        self.connect()

    # 提交
    def submit(self):
        self.__conn.commit()
